<?php

namespace backend\controllers;

use zhongkefu\zhongkefu;
use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use zhongkefu\helpers\AdminNav;
use zhongkefu\helpers\MysqlBackup;
use common\models\adminlog\AdminLog;


/**
 * DbManageController implements the CRUD actions for User model.
 */
class DbmanageController extends BackendController
{
    //public $layout=false;//设置当前默认布局文件为假  
     
	public function actionIndex()
    {
		$fileinfo = $this->actionMscandir(Yii::getAlias('@runtime') . '/_backup/');
		return $this->render('index',['fileinfo'=>$fileinfo]);
    }
	
    /**
     * 数据库备份
     */
    public function actionBackup(){

		//Dbmanage::backup();
		$sql = new \zhongkefu\helpers\MysqlBackup();
        $tables = $sql->getTables();
        if (!$sql->StartBackup()) {
            //render error
            
			yii::$app->getSession()->setFlash('error','数据库备份失败');
            die;
        }

        foreach ($tables as $tableName) {
            $sql->getColumns($tableName);
        }

        foreach ($tables as $tableName) {
            $sql->getData($tableName);
        }
        $sqlFile = $sql->EndBackup();

        yii::$app->getSession()->setFlash('success','备份完毕！（已经自动备份到服务器里了,存放的目录是 '.$sqlFile.'）');
		Adminlog::addlog(yii::$app->user->id, '数据库备份操作');
        //Operatlog::addlog(yii::$app->user->id, '新增', '数据库备份');
        return $this->redirect(['index']);
    }

    /**
     * 数据库还原
     */
    public function actionRestore($name){
		$sql = new \zhongkefu\helpers\MysqlBackup();
		$flag=$sql->restore(Yii::getAlias('@runtime') . '/_backup/'.$name);
		if($flag){
			yii::$app->getSession()->setFlash('success','还原成功！');
		}else{
			yii::$app->getSession()->setFlash('error','还原失败！');
		}
		Adminlog::addlog(yii::$app->user->id, '数据库还原操作');
		return $this->redirect(['index']);
    }


	//数据库删除
	public function actionDel($name){
		unlink(Yii::getAlias('@runtime') . '/_backup/'.$name);
		Yii::$app->session->setFlash('success', '文件删除成功！');
		Adminlog::addlog(yii::$app->user->id, '数据库删除操作');
		return $this->redirect(['index']);
	}
	
	//数据库下载
	public function actionDown($file){
		$file=Yii::getAlias('@runtime') . '/_backup/'.$file;
		if(is_file($file)){
			$length = filesize($file);
			$showname =  ltrim(strrchr($file,'/'),'/');
			header("Content-Description: File Transfer");
			header('Content-Type: application/octet-stream');
			header('Content-Length:' . $length);
			if(preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
				header('Content-Disposition: attachment; filename="' . rawurlencode($showname) . '"');
			} else {
				header('Content-Disposition: attachment; filename="' . $showname . '"');
			}
			readfile($file);
			exit;
		} else {
			exit('文件已被删除！');
		}
		Adminlog::addlog(yii::$app->user->id, '数据库下载操作');
		return $this->redirect(['index']);
	}
	
	public function actionMscandir($dir){
	 $files = array();
	 $filesinfo = array();
	 if( $handle = opendir($dir)){
	  while(($file = readdir($handle))!== false){
	   if($file != ".." && $file != "."){
		if(is_dir($dir . "/" . $file)){
		 $files[$file] = $this->actionMscandir($dir . "/" . $file);
		}else{
		 $files[] = $file;
		}
	   }
	  }
	  closedir($handle);
	  }
	  foreach($files as $key => $val){
		  
		$time=filectime($dir."/".$val);//时间
		$filesinfo[$key]['name']=$val; //文件名
		$filesinfo[$key]['time']=date("Y-m-d",$time);
		$filesinfo[$key]['size']=$this->actionGetRealSize(filesize($dir."/".$val));//大小
	  }
	  return $filesinfo;
	}
	
	//单位自动转换函数 
	public function actionGetRealSize($size){ 
	  $kb = 1024;     //Kilobyte 
	  $mb = 1024 * $kb;  //Megabyte 
	  $gb = 1024 * $mb;  //Gigabyte 
	  $tb = 1024 * $gb;  //Terabyte 
		  
	  if($size < $kb) 
	  { 
		return $size." B"; 
	  } 
	  else if($size < $mb) 
	  { 
		return round($size/$kb,2)." KB"; 
	  } 
	  else if($size < $gb) 
	  { 
		return round($size/$mb,2)." MB"; 
	  } 
	  else if($size < $tb) 
	  { 
		return round($size/$gb,2)." GB"; 
	  } 
	  else
	  { 
		return round($size/$tb,2)." TB"; 
	  } 
	} 
}

?>